<template>
  <div class="chat" :style="{ zIndex: zIndex }">
    <div class="calling" v-show="callStatus === 4" @click="showHangup">
      <div class="calling-video" v-show="callType==='video'">
        <div class="small-video-wrap" direction="all" scale scale-min="0.8" scale-max="2">
          <video
            id="small-video"
            class="small-video"
            ref="local-video"
            :controls="false"
            :show-play-btn="false"
            :show-fullscreen-btn="false"
            :show-center-play-btn="false"
            muted
          />
        </div>
      <video
        class="big-video"
        ref="remote-video"
        :controls="false"
        :show-play-btn="false"
        :show-fullscreen-btn="false"
        :show-center-play-btn="false"
      />
      <div class="button-wrap" v-show="isShowHangup">
        <div class="button">
          <div class="icon no" @click="hangup">
            <van-icon name="phone" />
          </div>
          <span>挂断</span>
        </div>
      </div>
      </div>
      <div class="calling-audio" v-show="callType==='audio'">
        <div class="user">
          <img class="avatar" :src="contact.avatar" :alt="contact.name"/>
          <span >{{ tip }}</span>
        </div>
        <div class="button-wrap">
          <div class="button" >
            <div class="icon no" @click="hangup">
              <van-icon name="phone" />
            </div>
            <span>挂断</span>
          </div>
        </div>
      </div>
    </div>
    <div class="call" v-if="[1, 2, 3].includes(callStatus)">
      <div class="user">
        <img class="avatar" :src="contact.avatar" :alt="contact.name"/>
        <span>{{ tip }}</span>
      </div>
      <div class="button-wrap">
        <div class="button" v-if="[1, 3].includes(callStatus)">
          <div class="icon no" @click="reject">
            <van-icon name="phone" />
          </div>
          <span>挂断</span>
        </div>
        <div class="button" v-else>
          <div class="icon no" @click="hangup">
            <van-icon name="phone" />
          </div>
          <span>挂断</span>
        </div>
        <div class="button" v-show="callStatus === 1">
          <div class="icon ok" @click="recieve">
            <van-icon name="phone" />
          </div>
          <span>接听</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VideoCall from './videoCall'
import { mapGetters, mapActions } from 'vuex'
import globalEvent from '@/utils/event'
import ring from '@/assets/audio/Fairyland.ogg'

export default {
  data() {
    return {
      callStatus: 0, // 0-无通话，1-被呼叫中等待接听，2-呼叫中等待对方接听 3-连接中,4-通话中
      callType: 'audio',
      user: null,
      videoCall: null,
      contact: {
        name: '印度啊三',
        avatar: 'https://img.phb123.com/uploads/allimg/170103/17-1F1031Q02T22.jpg',
        id: 'abdddd'
      },
      audio: null,
      callTimeout: 30,
      isShowHangup: true,
      hangUpTimer: null
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    tip() {
      const type = this.callType === 'audio' ? '语音' : '视频'
      if (this.callStatus === 1) {
        return `${this.contact.name}邀请你进行${type}通话`
      } else if (this.callStatus === 2) {
        return `正在${type}呼叫${this.contact.name}`
      } else if (this.callStatus === 3) {
        return '连接中...'
      } else {
        return `正在与${this.contact.name}进行${type}通话`
      }
    },
    zIndex() {
      return this.callStatus ? 99999 : -1
    }
  },
  created() {
    const audio = new Audio(ring)
    audio.loop = true
    audio.preload = 'auto'
    this.audio = audio
  },
  mounted() {
    this.init()
    globalEvent.on('videoCall', (contactId, callType) => {
      this.call(contactId, callType)
    })
  },
  onUnload() {
    this.unload()
  },
  methods: {
    ...mapActions({ getContactInfo: 'contact/getContactInfo' }),
    init() {
      const { id: userId } = this.userInfo
      const socket = this.$socket
      const videoCall = new VideoCall({
        socket,
        sockets: this.sockets,
        userId,
        timeout: this.callTimeout * 1000,
        remoteVideoEle: this.$refs['remote-video'],
        localVideoEle: this.$refs['local-video']
      })
      this.videoCall = videoCall
      window.videoCall = videoCall
      this.mounteListener()
    },
    mounteListener() {
      const statusEnum = {
        free: 0,
        called: 1,
        calling: 2,
        connecting: 3,
        busy: 4
      }
      this.videoCall.on('status', ({ status, callType }) => {
        const callStatus = statusEnum[status]
        this.callType = callType
        this.callStatus = callStatus
        if (callStatus === 1 || callStatus === 2) {
          this.rung()
        } else {
          this.stopRung()
        }
        if (callStatus === 4) {
          this.isShowHangup = false
        }
      })
      this.videoCall.on('message', msg => {
        if (typeof msg === 'string') {
          this.$toast(msg)
        } else {
          const { type, text } = msg
          console.log('$toast[type]---', type)
          this.$toast[type](text)
        }
      })
      this.videoCall.on('callConfirm', ({ data }) => {
        this.contact.name = data.name
        this.contact.avatar = data.avatar
        this.contact.id = data.id
      })
      this.videoCall.on('requestCall', data => {
        console.log('videcall.vue 发起通话请求')
      })
      this.videoCall.on('error', data => {
        console.log('videcall error', data)
      })
    },
    unload() {
      this.videoCall = null
      window.videoCall = null
    },
    async call(contactId, callType) {
      if (this.videoCall) {
        const contactInfo = await this.getContactInfo(contactId)
        if (!contactInfo.online) {
          this.$toast.fail('该用户不在线')
          return
        }
        this.contact.name = contactInfo.name
        this.contact.avatar = contactInfo.avatar
        await this.videoCall.call(contactInfo.id, callType, this.userInfo)
      }
    },
    recieve() {
      this.videoCall.emit('callRecieve', this.contact.id)
    },
    reject() {
      this.videoCall.emit('callReject', this.contact.id)
    },
    hangup() {
      if (this.videoCall) {
        this.videoCall.hangUp('对方已经挂断')
      }
    },
    showHangup() {
      this.isShowHangup = true
      this.hangUpTimer = setTimeout(() => {
        this.isShowHangup = false
      }, 3000)
    },
    rung() {
      this.audio.play()
      // this.$refs.audio.play()
    },
    stopRung() {
      this.audio.pause()
      this.audio.currentTime = 0
      // this.$refs.audio.stop()
    }
  },
  sockets: {
    // video_call(e) {
    //   console.log('video_call', e)
    // }
  }
}
</script>

<style lang="scss" scoped>
.chat {
  display: flex;
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: -1;
  top: 0;
  left: 0;
  .calling {
    width: 100%;
    height: 100%;
    background-color: #01212d;
    .calling-video{
      width: 100%;
      height: 100%;
      .small-video-wrap {
        /* outline: 1px solid blue; */
        width: 100px;
        min-height: 167px;
        z-index: 100;
        .small-video {
          width: 100%;
          height: 100%;
        }
      }
      .big-video {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
      }
    }
    .calling-audio{
      width: 100%;
      height: 100%;
    }
  }
}

.call {
  width: 100%;
  height: 100%;
  background-color: #01212d;
  position: relative;
}

.user {
  width: 200px;
  height: 240px;
  font-size: 16px;
  color: white;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -100%);
  text-align: center;
  .avatar {
    width: 200px;
    height: 200px;
  }
}
.button-wrap {
  width: 100%;
  display: flex;
  justify-content: space-around;
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 99999;
  .button {
    text-align: center;
    color: #f5f5f5;
  }
}

.icon {
  margin-bottom: 10px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  color: $white;
  text-align: center;
  .van-icon{
    font-size: 30px;
    line-height: 50px;
  }
}

.icon.ok {
  background-color: rgb(13, 156, 13);
}

.icon.no {
  background-color: rgb(211, 29, 29);
  transform: rotate(135deg)
}

.hide {
  display: none;
}
</style>
